<template>
  <div class="app-container">
    <el-row>
<!-- 登录界面-->
      <el-col :span="15">
        <el-card>
          <div slot="header" class="clearfix">
            <span>订单列表</span>
            <el-button style="float: right; padding: 3px 0" type="text">刷新</el-button>
          </div>
          <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="预定抢购时间" align="center" prop="presetTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.presetTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="用户cookie" align="center" prop="cookie" width="180" >
              <template slot-scope="scope">
                <el-popover
                  placement="top-start"
                  title="用户cookie"
                  width="500"
                  trigger="hover"
                  >
                  <p class="table2" slot="reference">
                    {{scope.row.cookie}}
                  </p>
                  <el-button  type="text" size="mini" v-clipboard:copy=scope.row.cookie v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制</el-button>
                  <div>
                    {{scope.row.cookie}}
                  </div>

                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="cookie登记时间" align="center" prop="cookieRecordTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.cookieRecordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="免息券类型" align="center" prop="mxType" width="180">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.mx_type"
                  :value="scope.row.mxType"
                >
                </dict-tag>
              </template>
            </el-table-column>
            <el-table-column label="订单状态" align="center" prop="status" />
            <el-table-column label="用户id" align="center" prop="createUserId" />
            <el-table-column label="订单实际收入" align="center" prop="realIncome" />
            <el-table-column label="备注" align="center" prop="remark" />

          </el-table>


        </el-card>

      </el-col>
<!--扫码界面 -->
      <el-col :span="8" style="margin-left: 4px">
        <el-card>
          <div slot="header" class="clearfix">
            <span>手机号登陆</span>
            <el-button style="float: right; padding: 3px 0" type="text">-|-</el-button>
          </div>
          <div class="image-container">
            <img  ref="vcImg" style="width: 200px;height: 200px" :src="url"/>
          </div>
          <el-form :model="queryParams" style="margin-top: 10px; align-content: center" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
            <el-tabs v-model="queryParams.activeName" >
              <el-tab-pane label="添加新订单" name="add">
                <el-form-item label="省份" prop="province">
                  <el-select v-model="queryParams.province" placeholder="请选择" clearable @change="getCityList(queryParams.province)">
                    <el-option
                      v-for="dict in provinceList"
                      :key="dict.id"
                      :label="dict.province"
                      :value="dict.code"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="城市" prop="city" >
                  <el-select v-model="queryParams.city" placeholder="选择省份后选择城市" clearable size="small" filterable>
                    <el-option
                      v-for="dict in cityList"
                      :key="dict.cityCode"
                      :label="dict.city"
                      :value="dict.cityCode"
                    />
                  </el-select>
                  <br/>
                  <el-button  type="text" size="mini" v-clipboard:copy="baseUrl+queryParams.province+'&city='+queryParams.city+'&createUserId='+ queryParams.createUserId+'&activeName='+queryParams.activeName" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制用户登陆链接</el-button>

                </el-form-item>

              </el-tab-pane>
              <el-tab-pane label="更新现有用户Cookie" name="update">

                <el-form-item label="省份" prop="province">
                  <el-select v-model="queryParams.province" placeholder="请选择" clearable @change="getCityList(queryParams.province)">
                    <el-option
                      v-for="dict in provinceList"
                      :key="dict.id"
                      :label="dict.province"
                      :value="dict.code"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="城市" prop="city" >
                  <el-select v-model="queryParams.city" placeholder="选择省份后选择城市" clearable size="small" filterable>
                    <el-option
                      v-for="dict in cityList"
                      :key="dict.cityCode"
                      :label="dict.city"
                      :value="dict.cityCode"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="用户id" prop="createUserId" >
                  <el-input v-model="queryParams.createUserId" placeholder="请输入客户Id(不输入会生成一个独立的新订单)" width="200"></el-input>
                  <el-button round @click="userOpen=true">选择用户</el-button>
                  <br/>
                  <el-button  type="text" size="mini" v-clipboard:copy="baseUrl+queryParams.province+'&city='+queryParams.city+'&createUserId='+ queryParams.createUserId+'&activeName='+queryParams.activeName" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制用户登陆链接</el-button>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="添加现有用户订单" name="addUserOrder">

                <el-form-item label="省份" prop="province">
                  <el-select v-model="queryParams.province" placeholder="请选择" clearable @change="getCityList(queryParams.province)">
                    <el-option
                      v-for="dict in provinceList"
                      :key="dict.id"
                      :label="dict.province"
                      :value="dict.code"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="城市" prop="city" >
                  <el-select v-model="queryParams.city" placeholder="选择省份后选择城市" clearable size="small" filterable>
                    <el-option
                      v-for="dict in cityList"
                      :key="dict.cityCode"
                      :label="dict.city"
                      :value="dict.cityCode"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="用户id" prop="createUserId" >
                  <el-input v-model="queryParams.createUserId" placeholder="请输入客户Id(不输入会生成一个独立的新订单)" width="200"></el-input>
                  <el-button round @click="userOpen=true">选择用户</el-button>
                  <br/>
<!--                  <el-button round @click="generateUserLoginUrl()" type="primary"  style="margin-top: 5px">生成用户登陆链接</el-button>-->
                  <el-button  type="text" size="mini" v-clipboard:copy="baseUrl+queryParams.province+'&city='+queryParams.city+'&createUserId='+ queryParams.createUserId+'&activeName='+queryParams.activeName" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制用户登陆链接</el-button>
                </el-form-item>
              </el-tab-pane>
            </el-tabs>

          </el-form>
          <div style="padding: 14px;">
            <span>当前状态:{{loginStatus}}</span>
            <div class="bottom clearfix">
              <el-button type="text" class="button" @click="getLoginORCode">刷新二维码</el-button>
            </div>
          </div>
          <div>

          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户信息</span>
        <el-button type="text" style="margin-left: 10px" size="mini" v-clipboard:copy="userCookie" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制登陆信息</el-button>
      </div>
      <div>
            <el-button round @click="generateUserLoginUrl()" type="primary"  style="margin-top: 5px">生成用户登陆链接</el-button>
        <div>用户登陆链接:{{openUrl}}</div>
      </div>
      <br/>
      <div>{{userCookie}}</div>
    </el-card>

    <customerInfo ref="userInfo" :dialogVisible="userOpen" @chooseUser="chooseUser" @close="closeUserInfo"></customerInfo>
  </div>
</template>

<script>
import { addAdminOrder, addOrder, delOrder, getOrder, listOrder, updateOrder } from '@/api/mx/order'
import axios from 'axios'
import { cityList, listProvince } from '@/api/cityManagement'
import  customerInfo from '@/views/components/customerSelect/customerSelect'

export default {
  dicts:['login_status','order_status','mx_type'],
  name: "/loginJd",
  components: {customerInfo},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // mx订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        fishAccount: null,
        customerName: null,
        address: null,
        phoneNumber: null,
        mxType: null,
        status: null,
        createUserId: null,
        goodsOriginalPrice: null,
        goodsNowPrice: null,
        goodsAmount: null,
        orderPrice: null,
        cashback: null,
        realIncome: null,
        activeName: 'add',
        resCookie:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "下单时间不能为空", trigger: "blur" }
        ],
      },
      /************************************ 登陆**************************************/
      url: null,//登陆二维码
      loginInfo:null,//轮询扫码响应的信息
      QRCodeKey:null,
      wlfstk_smdl:null,//登陆参数
      loginStatus:null,//登陆情况
      userCookie:'',//用户的cookie
      provinceList: [],//省份列表
      cityList:[],//城市列表

      userOpen:false,//用户弹窗
      listParams:{
        pageNum: 1,
        pageSize: 5,
      },
      openUrl: null,//用户打开链接
      baseUrl: 'http://42.194.242.207:80/open/userJdLogin?province='
    };
  },
  created() {
    this.getList();
    this.getProvince();
  },
  methods: {
    /** 查询mx订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.listParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        createTime: null,
        fishAccount: null,
        customerName: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加mx订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改mx订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除mx订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jd/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /**获取京东登陆二维码**/

    getLoginORCode() {
      if (this.queryParams.province === null || this.queryParams.province === undefined) {
        this.$message.error('请选择省份')
        return;
      }else if (this.queryParams.city === null || this.queryParams.city === undefined) {
        this.$message.error('请选择城市')
        return
      } else {
        axios.post('/py/getQRcode', this.queryParams).then(response => {
          //const blob = new Blob([response.data], { type: response.headers['content-type'] }); // 创建Blob对象
          //saveAs(blob, 'image.jpg'); // 调用saveAs方法保存文件到本地
          if (response.status === 200) {

            this.url = "data:image/png;base64," +response.data.qrcode

            this.QRCodeKey=response.data.cookies
            this.wlfstk_smdl=response.data.wlfstk_smdl;
            this.proxx=response.data.proxx;
            this.getLoginResult()

          }

        })
          .catch(error => {
            console.log(error);
          });
      }
    },
    //获取登陆结果
    //获取登陆结果
    getLoginResult() {
      let data={
        'wlfstk_smdl': this.wlfstk_smdl+'', 'cookies': this.QRCodeKey+'','proxx':this.proxx
      }
      axios.defaults.headers.common['Content-Type'] = 'application/json';
      this.pollingTimer = setInterval(() => {
        axios.post('/py/getresult', data).then(res => {
          console.log(res)
          this.loginStatus = res.data.msg
          this.userCookie=res.data.qrcookies
          if (res.data.code === 200) {
            clearInterval(this.pollingTimer) // 停止轮询
            console.log('请求成功，停止轮询')
            //将用户信息存入数据库中
            let data={
              cookie: this.userCookie,
              activeName: this.queryParams.activeName,
              createUserId: this.queryParams.createUserId
            }
            addAdminOrder(data).then(res=>{
              if (res.code === 200) {
                this.$message.success('获取成功')
                this.getList();
              }
            })
          }else if (res.data.code === 500) {
            clearInterval(this.pollingTimer) // 停止轮询
            this.loginStatus = '获取失败，请选择您当前所在地区';
            this.$message.error("获取失败，请选择您当前所在地区")
          }
        })
          .catch(error => {
            console.error(error)
          })
      }, 3000) // 每3秒执行一次请求
    },


    beforeDestroy() {
      clearInterval(this.pollingTimer) // 组件销毁前清除定时器
    },
/******************获取省份信息 ********************/
    getProvince(){
      listProvince().then(res=>{
        if (res.code === 200) {
          this.provinceList = res.data
        }
      })
    },
    /******************获取城市信息 ********************/
    getCityList(code){

      if (code === null) {
        return
      }
      let obj={}
      obj = this.provinceList.find((item) => { // 这里的provincelist就是上面省的数据
        return item.code === code // 筛选出匹配数据，这里的id是接口数据中的每一项的id
      })
      let data={
        provinceId : obj.id
      }
      //获取城市列表
      cityList(data).then(res=>{
        if (res.code === 200) {
          this.cityList = res.data
        }

      })
    },
    onCopySuccess(){
      this.$message.success('信息复制成功')
    },
    onCopyError(){
      this.$message.error('复制失败')
    },

    /**
     * 用户界面选择用户
     */
    chooseUser(user){
      //选择成功
      this.$message.success("选择成功")
      this.queryParams.createUserId = user.customerId
      this.userOpen=false
    },
    /**
     * 关闭用户列表
     */
    closeUserInfo(){
      this.userOpen=false
    },
    /**
     * 生成用登陆的url
     */
    generateUserLoginUrl() {
      let province = this.queryParams.province
      let city = this.queryParams.city
      let createUserId = this.queryParams.createUserId
      let activeName = this.queryParams.activeName
      //let baseUrl = "http://localhost:80"
      let baseUrl = "http://42.194.242.207:80"
      //"http://42.194.242.207:80/open/userJdLogin?province="+this.queryParams.province+"&city"+this.queryParams.city+'&createUserId'+ this.queryParams.createUserId+"&activeName"+this.queryParams.activeName
      let url = baseUrl+'/open/userJdLogin?province='+province+'&city='+city+'&createUserId='+createUserId+'&activeName='+activeName
      this.openUrl = url
     /*  navigator.clipboard.writeText(url)
        .then(() => {
          this.$message.success('复制登陆链接成功')
        })
        .catch(() => {
          this.$message.error('复制失败')
        }) */

    },
  }
};
</script>

<style scoped>
.table2  {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  /* 如果希望图片垂直居中整个视口，可以使用这行代码 */
}
</style>
